<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="getTitle" 
    :width="500" 
    @ok="handleSubmit" 
    showFooter
    destroyOnClose
  >
    <BasicForm @register="registerForm"/>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form/index';
  import { BasicDrawer, useDrawerInner} from '/@/components/Drawer';
  import { saveOrUpdateFieldLibrary } from '../api';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ColEx } from '/@/components/Form/src/types';
  const { t } = useI18n('');
  const { createMessage } = useMessage();

  const emit = defineEmits(['success', 'register']);
  const attrs = useAttrs()
  const isUpdate = ref(true);
  const record = ref<any>({});

  const inputFormSchemas: FormSchema[] = [
  {
    label: '',
    field: 'id',
    component: 'Input',
    show: false,
  },
  {
    label: t('字段名称'),
    field: 'fieldName',
    component: 'Input',
    componentProps: {
      maxlength: 64,
    },
  },
  {
    label: t('字段Key'),
    field: 'fieldKey',
    component: 'Input',
    required: true,
    componentProps: {
      maxlength: 200,
    },

  },
  {
    label: t('备注信息'),
    field: 'remark',
    component: 'InputTextArea',
    componentProps: {
      maxlength: 500,
    },
    colProps: { lg: 24, md: 24 },
  }
];


  const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
    labelWidth: 80,
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  });
  
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await resetFields();
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate;
      record.value = data.record
      setFieldsValue({ 
        ...record.value
      })

    } finally {
      setDrawerProps({ loading: false})
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增消息字段' : '编辑消息字段'));

  async function handleSubmit() {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});

      await saveOrUpdateFieldLibrary({...values}, unref(isUpdate));
      closeDrawer();
      createMessage.success(`${getTitle.value}成功`)
      emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>
